#!/usr/bin/env node

/**
 * Module dependencies.
 */
//在本地的命令行执行 node ./trigger_jenkins.js , 或者把此命令放到package.json的script字段
const { Command } = require('commander');
const program = new Command();
const request = require('request')
let environmental = 'test'
// console.log(program)

program.version('0.0.1')
    .description('这是一个命令行工具')
    .option('-project,--project [name]', 'build you develop project name')
    .option('-token,--apitoken [apitoken]', 'send your api token')
    .option('-author,--author [name]', 'send your author')
    .option('-trigger,--triggerName [name]', 'send your triggerName')
    .option('-branch,--gitBranch [name]', 'send your gitBranch/tags');

program.on('--help', function () {
    console.log('')
    console.log('Examples:');
    console.log('  $ custom-help --help');
    console.log('  $ custom-help -h');
});

// error on unknown commands
program
    .command('setup [env]')
    .description('run setup commands for all envs')
    .action(function (env, options) {
        const mode = options.setup_mode || "normal";
        env = env || 'all';
        console.log('setup for %s env(s) with %s mode', env, mode);
        environmental = env;
        //目前只有测试和开发允许默认构建dev_branch分支
        if (env == 'test' || env == 'dev') {
            autoJenkis()
        }
        //如果是正式环境一定需要配置对应的分支或者tag
        if (env == 'build' && program.gitBranch && program.gitBranch !== 'xx') {
            autoJenkis()
        }
    });

program.parse(process.argv);

function autoJenkis() {    
    let apiToken = program.token || '115ab8105eb625e8e0523f8ea387924aba'   //个人的apitoken , 路径:jenkins界面右上角用户名->设置->添加新Token
    let author = program.author || 'zhangli'  //用户名
    let project = program.project || 'vue-webim-test' // 项目名
    let headerStr = `http://${author}:${apiToken}@192.168.197.95:8080/job/${project}/buildWithParameters`
    let triggerName = program.triggerName || 'jenikis@rfchina.com' //jenkins->项目->配置->构建触发器->触发远程构建->填写你的身份验证令牌
    let gitBranch = program.gitBranch || '*/dev_branch'
    let url = headerStr + `?token=${triggerName}&GIT_BRANCH=${encodeURI(gitBranch)}` //uploadComponentName为要带过去的参数,可以去掉 
    console.log(url)
    // 触发更新
    request({
        url,
        method: "get",
        json: true,
        headers: {
            "content-type": "application/json"
        }
    }, function (error, response, body) {
        console.log()
        if (error) {
            console.log('触发jenkins编译失败', error)
        } else {
            console.log('触发jenkins编译成功')
        }
    })
}


// autoJenkis()


